package com.jsl.action;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class SsoAction2 {

    /**
     * 获取token
     */

    public void getToken() {

        String url = "http://192.168.46.62:8808/ssologin/getToken";

        Map<String, String> params = new HashMap<>();

        params.put("appid", "demo1");

        params.put("loginid", "sw");

        String s = SsoAction.doPost(url, params);

        System.out.println(s);

//获得的token: 659C43561254716F8961A2586888BD17288178101C86582821E50E190F941A72

    }


    /**
     * 带上token访问ecology页面
     */
    public void visitPage() {

        String token = "659C43561254716F8961A2586888BD17288178101C86582821E50E190F941A72";

        String url = "http://192.168.46.62:8808/systeminfo/version.jsp";

        Map<String, String> params = new HashMap<>();

        params.put("ssoToken", token);

        String s = SsoAction.doPost(url, params);

        System.out.println(s); // 能成功返回内容

    }


    /**
     * 发送带参数的GET请求
     *
     * @param url    请求地址
     * @param params 参数Map，键值对形式
     * @return 响应内容
     */
    public static String sendGetRequest(String url, Map<String, String> params) {
        // 拼接查询参数
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            try {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = URLEncoder.encode(entry.getValue(), "UTF-8");
                    sb.append(key).append("=").append(value).append("&");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.deleteCharAt(sb.length() - 1); // 删除最后一个 &
        }

        String requestUrl = sb.toString();

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(new HttpGet(requestUrl))) {

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, StandardCharsets.UTF_8);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @return
     */

    public static String doPost(String url, String params) throws Exception {


        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);// 创建httpPost

        httpPost.setHeader("Accept", "application/json");

        httpPost.setHeader("Content-Type", "application/json");

        String charSet = "UTF-8";

        StringEntity entity = new StringEntity(params, charSet);

        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;


        try {


            response = httpclient.execute(httpPost);

            StatusLine status = response.getStatusLine();

            int state = status.getStatusCode();

            if (state == HttpStatus.SC_OK) {

                HttpEntity responseEntity = response.getEntity();

                String jsonString = EntityUtils.toString(responseEntity);

                return jsonString;

            } else {

            }

        } finally {

            if (response != null) {

                try {

                    response.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            try {

                httpclient.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return null;

    }


}
